<?php
namespace App\Common\Utill;

use Illuminate\Support\Facades\Config;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Utill
{
    /**
     * 订单场景
     */
    protected static $orderSceneArr = [
        10,//默认值
        11,//充值零钱订单
        12,//充值风筝订单
        13,//背包订单
        14,//守护订单
        15,//服务订单
        16,//缴纳服务费&保证金订单
        17,//课程金充值订单
        18,//心动热线视频接通订单
        19,//生成能量包订单
        20,//直播能量包订单
        21,//视频能量包订单
        22,//提现订单
    ];

    /**
     * CURL请求
     * @param $url string 请求url地址
     * @param $method string 请求方法 get post
     * @param mixed $postfields post数据数组
     * @param array $headers 请求header信息
     * @param bool|false $debug  调试开启 默认false
     * @param bool|false $version HTTP_VERSION_1_1 默认 false
     * @return mixed
     */
    public static function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false,$version = false)
    {
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        if ($version) {
            curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        }
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method);
        switch ($method) {
            case "POST":
            case "DELETE":
            case "PATCH":
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
        }

        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }

        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
            curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        }

        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);

        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);

        $requestinfo = curl_getinfo($ci);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }




    /**
     * http Post请求
     * @param string $url 接口地址
     * @param array $param 传递参数
     * @param array $header 头参数
     * @return mixed|string
     */
    public static function curlPost($url = '', $param = [], $header = [])
    {
        try {
            if (empty($url)) {
                throw  new \Exception('URL Not Empty');
            }
            $ch = curl_init(); //初始化init方法
            curl_setopt($ch, CURLOPT_URL, $url); //指定url
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //忽略证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //忽略证书
            curl_setopt($ch, CURLOPT_SSLVERSION, 1);//忽略证书
            curl_setopt($ch, CURLOPT_HEADER, 0);//显示返回的header区域内容
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);//设置超时时间
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设定请求返回结果
            curl_setopt($ch, CURLOPT_POST, 1); //声明使用post方式进行发送
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param)); //post发送什么数据
            if (!empty($header)) {
                $headerData = array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length: ' . strlen(json_encode($param)),
                );
                foreach ($header as $key => $item) {
                    $headerData[] = $key . ':' . $item;
                }
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headerData);
            }
            $data = curl_exec($ch); //发送请求
            curl_close($ch); //关闭curl
            return json_decode($data, true);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }




    /**
     * 元转分
     * @param $price
     * @return float|int
     */
    public static function rmbToPenny($price)
    {
        // 元转分
        return intval(strval(floatval(abs($price)) * 100));
    }

    /**
     * 分转元
     * @param $money
     * @param bool $is_
     * @return string
     */
    public static function pennyToRmb($money ,$is_ = false)
    {
        // 分转元
        if($is_){
            return sprintf("%.2f", $money / 100);
//            return number_format( $money / 100,2,'.',',');
        }
        return (string) abs($money / 100);
    }

    /**
     * 获取订单sn 19位（20220802弃用）
     * @return string
     */
    public static function get_order_sn_old()
    {
        $time = explode(' ', microtime());
        $time = $time[1] . $time[0] * 1000;
        $time = explode('.', $time);
        $time = isset($time[1]) ? $time[1] : 0;
        $time = date('YmdHis') + $time;
        mt_srand((double) microtime() * 1000000);
        return $time . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 获取订单sn 26位（20220802新版）
     * @param int $scene 下单场景
     * @param $id 订单所有者id，用户ID
     * @return string
     */
    public static function get_order_sn($scene = 10, $id)
    {
        $scene = in_array($scene, self::$orderSceneArr) ? $scene : 10;
        $micTime = bcmul(microtime(true), 10000);
        $micTimeStr = str_pad((substr($micTime, 0, 10) . substr($micTime, 10, 4)), 14, '0', STR_PAD_LEFT);
        $idStr = str_pad($id, 10, '0', STR_PAD_LEFT);
        $orderSn = strval($scene);
        for ($i = 0; $i < 5; $i++) {
            $flag = $i*2;
            $orderSn .= $micTimeStr[$flag] . $micTimeStr[$flag + 1] . $idStr[$flag] . $idStr[$flag + 1];
        }
        $orderSn .= substr($micTimeStr, 10, 4);
        return $orderSn;
    }

    /**
     * 获取32为数字字符串
     * @return string
     */
    public static function get_order_sn_32()
    {
        $time = explode(' ', microtime());
        $time = $time[1] . $time[0] * 1000;
        $time = explode('.', $time);
        $time = isset($time[1]) ? $time[1] : 0;
        $time = date('YmdHis') + $time;
        mt_srand((double) microtime() * 1000000);
        return $time . str_pad(mt_rand(1, 999999999999), 18, '0', STR_PAD_LEFT);
    }

    /**
     * 获取TradeSn
     * @return string
     */
    public static function getTradeSn()
    {
        $time = explode(' ', microtime());
        $time = $time[1] . $time[0] * 1000;
        $time = explode('.', $time);
        $time = isset($time[1]) ? $time[1] : 0;
        $time = date('YmdHis') . $time;
        return $time . str_pad(mt_rand(1, 99999), 6, '0', STR_PAD_LEFT);
    }
    /**
     * 生成随机字符串
     * @param $param
     * @return string
     */
    public static function getRandom($param){
        $str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $key = "";
        for($i=0;$i<$param;$i++)
        {
            $key .= $str.mt_rand(0,32);    //生成php随机数
        }
        return $key;
    }

    public static function substr_cut($user_name,$head,$foot)
    {
        $strlen     = mb_strlen($user_name, 'utf-8');
        $firstStr     = mb_substr($user_name, 0, $head, 'utf-8');
        $lastStr     = mb_substr($user_name, -$foot, $foot, 'utf-8');
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - ($head+$foot)) . $lastStr;
    }

    /**
     * php获取中文字符拼音首字母
     * @param $str
     * @return string|null
     */
    public static function getFirstCharter($str)
    {
        if(empty($str))
        {
            return '';
        }
        $fchar=ord($str[0]);
        if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str[0]);
        $s1=iconv('UTF-8','gb2312//TRANSLIT//IGNORE',$str);
        $s2=iconv('gb2312','UTF-8//TRANSLIT//IGNORE',$s1);
        $s=$s2==$str?$s1:$str;
        $asc=ord($s[0])*256+ord($s[1])-65536;
        if($asc>=-20319&&$asc<=-20284) return 'A';
        if($asc>=-20283&&$asc<=-19776) return 'B';
        if($asc>=-19775&&$asc<=-19219) return 'C';
        if($asc>=-19218&&$asc<=-18711) return 'D';
        if($asc>=-18710&&$asc<=-18527) return 'E';
        if($asc>=-18526&&$asc<=-18240) return 'F';
        if($asc>=-18239&&$asc<=-17923) return 'G';
        if($asc>=-17922&&$asc<=-17418) return 'H';
        if($asc>=-17417&&$asc<=-16475) return 'J';
        if($asc>=-16474&&$asc<=-16213) return 'K';
        if($asc>=-16212&&$asc<=-15641) return 'L';
        if($asc>=-15640&&$asc<=-15166) return 'M';
        if($asc>=-15165&&$asc<=-14923) return 'N';
        if($asc>=-14922&&$asc<=-14915) return 'O';
        if($asc>=-14914&&$asc<=-14631) return 'P';
        if($asc>=-14630&&$asc<=-14150) return 'Q';
        if($asc>=-14149&&$asc<=-14091) return 'R';
        if($asc>=-14090&&$asc<=-13319) return 'S';
        if($asc>=-13318&&$asc<=-12839) return 'T';
        if($asc>=-12838&&$asc<=-12557) return 'W';
        if($asc>=-12556&&$asc<=-11848) return 'X';
        if($asc>=-11847&&$asc<=-11056) return 'Y';
        if($asc>=-11055&&$asc<=-10247) return 'Z';
        return null;
    }

    /**
     * 移除空值的key
     * @param $para
     * @return array
     * @author Leo
     */
    public static function paraFilter($para)
    {
        $paraFilter = [];
        foreach ($para as $key => $val) {
            if ($val === '' || $val === null) {
                continue;
            }
            if (!is_array($para[$key])) {
                $para[$key] = is_bool($para[$key]) ? $para[$key] : trim($para[$key]);
            }

            $paraFilter[$key] = $para[$key];
        }

        return $paraFilter;
    }

    /**
     * 微信H5协议支付请求处理
     * @param $Url
     * @param $domainName
     * @return string
     * @throws \WxPayException
     */
    public static function wxPayH5($Url ,$domainName)
    {
        $_ch = curl_init();
        curl_setopt($_ch, CURLOPT_URL, $Url);
        if (strpos($Url, 'https') === 0) {
            curl_setopt($_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($_ch, CURLOPT_SSL_VERIFYHOST, 2);
        }
        $_headers['CLIENT-IP']       = $_SERVER['REMOTE_ADDR'];
        $_headers['X-FORWARDED-FOR'] = $_SERVER['REMOTE_ADDR'];
        $_header_arr = array();
        foreach( $_headers as $n => $v ) {
            $_header_arr[] = $n . ':' . $v;
        }
        curl_setopt($_ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($_ch, CURLOPT_HTTPHEADER , $_header_arr);  //构造IP
        curl_setopt($_ch, CURLOPT_CONNECTTIMEOUT, 5); // 连接超时（秒）
        //微信那边填的微信授权域
        curl_setopt ($_ch, CURLOPT_REFERER, $domainName);
        curl_setopt($_ch, CURLOPT_TIMEOUT, 5); // 执行超时（秒）
        $_out_put = curl_exec($_ch);
        if($_out_put === false){
            echo curl_error($_ch);die;
        }
        curl_close($_ch);
        //匹配出支付链接
        preg_match('/weixin(.*)"/', $_out_put, $_match);
        if( ! isset($_match[1]) ){
            throw new \WxPayException('无法获取支付链接:' . $_out_put);
        }
        $_client_pay_url = 'weixin'.$_match[1];
        return $_client_pay_url;
    }

    /**
     * 友好时间显示
     * @param $time
     * @return bool|string
     */
    public static function friend_date($time)
    {
        if (!$time)
            return false;
        $fdate = '';
        $d = time() - intval($time);
        $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
        $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
        $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
        $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
        $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
        $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
        $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
        if ($d == 0) {
            $fdate = '刚刚';
        } else {
            switch ($d) {
                case $d < $atd:
                    $fdate = date('Y年m月d日', $time);
                    break;
                case $d < $td:
                    $fdate = '后天' . date('H:i', $time);
                    break;
                case $d < 0:
                    $fdate = '明天' . date('H:i', $time);
                    break;
                case $d < 60:
                    $fdate = $d . '秒前';
                    break;
                case $d < 3600:
                    $fdate = floor($d / 60) . '分钟前';
                    break;
                case $d < $dd:
                    $fdate = floor($d / 3600) . '小时前';
                    break;
                case $d < $yd:
                    $fdate = '昨天' . date('H:i', $time);
                    break;
                case $d < $byd:
                    $fdate = '前天' . date('H:i', $time);
                    break;
                case $d < $md:
                    $fdate = date('m月d日 H:i', $time);
                    break;
                case $d < $ld:
                    $fdate = date('m月d日', $time);
                    break;
                default:
                    $fdate = date('Y年m月d日', $time);
                    break;
            }
        }
        return $fdate;
    }

    /**
     * 返回两个时间的相距时间，*年*月*日*时*分*秒
     * @param int $one_time 时间一
     * @param int $two_time 时间二
     * @param int $return_type 默认值为0，0/不为0则拼接返回，1/*秒，2/*分*秒，3/*时*分*秒/，4/*日*时*分*秒，5/*月*日*时*分*秒，6/*年*月*日*时*分*秒
     * @param array $format_array 格式化字符，例，array('年', '月', '日', '时', '分', '秒')
     * @return String or false
     */
    public static function getRemainderTime($one_time, $two_time, $return_type=0, $format_array=array('年', '月', '日', '时', '分', '秒'))
    {
        if ($return_type < 0 || $return_type > 6) {
            return false;
        }
        if (!(is_int($one_time) && is_int($two_time))) {
            return false;
        }
        $remainder_seconds = abs($one_time - $two_time);
        //年
        $years = 0;
        if (($return_type == 0 || $return_type == 6) && $remainder_seconds - 31536000 > 0) {
            $years = floor($remainder_seconds / (31536000));
        }
        //月
        $monthes = 0;
        if (($return_type == 0 || $return_type >= 5) && $remainder_seconds - $years * 31536000 - 2592000 > 0) {
            $monthes = floor(($remainder_seconds - $years * 31536000) / (2592000));
        }
        //日
        $days = 0;
        if (($return_type == 0 || $return_type >= 4) && $remainder_seconds - $years * 31536000 - $monthes * 2592000 - 86400 > 0) {
            $days = floor(($remainder_seconds - $years * 31536000 - $monthes * 2592000) / (86400));
        }
        //时
        $hours = 0;
        if (($return_type == 0 || $return_type >= 3) && $remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400 - 3600 > 0) {
            $hours = floor(($remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400) / 3600);
        }
        //分
        $minutes = 0;
        if (($return_type == 0 || $return_type >= 2) && $remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400 - $hours * 3600 - 60 > 0) {
            $minutes = floor(($remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400 - $hours * 3600) / 60);
        }
        //秒
        $seconds = $remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400 - $hours * 3600 - $minutes * 60;
        $return = false;
        switch ($return_type) {
            case 0:
                if ($years > 0) {
                    $return = $years . $format_array[0] . $monthes . $format_array[1] . $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
                } else if ($monthes > 0) {
                    $return = $monthes . $format_array[1] . $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
                } else if ($days > 0) {
                    $return = $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
                } else if ($hours > 0) {
                    $return = $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
                } else if ($minutes > 0) {
                    $return = $minutes . $format_array[4] . $seconds . $format_array[5];
                } else {
                    $return = $seconds . $format_array[5];
                }
                break;
            case 1:
                $return = $seconds . $format_array[5];
                break;
            case 2:
                $return = $minutes . $format_array[4] . $seconds . $format_array[5];
                break;
            case 3:
                $return = $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
                break;
            case 4:
                $return = $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
                break;
            case 5:
                $return = $monthes . $format_array[1] . $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
                break;
            case 6:
                $return = $years . $format_array[0] . $monthes . $format_array[1] . $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
                break;
            default:
                $return = false;
        }
        return $return;
    }

    /**
     * Description:将秒数转换为00:00:00(时分秒格式）
     * Param:参数说明
     * [in] $times int n秒
     * [in] $_is bool 是否有秒
     * Return:返回值
     * 00:00:00（时分秒）
     */
    public static function time_conversion($times,$_is){
        $result = '00:00:00';
        if ($times>0){
            $hour = floor($times/3600);
            $minute = floor($times%3600/60);
            $second = floor(($times-60 * $minute) % 60);
            if ($hour < 10) {
                $hour = '0' . $hour;
            }
            if($minute<10){
                $minute = "0".$minute;
            }
            if($_is){
                if($second<10){
                    $second = "0".$second;
                }
                $result = $hour.':'.$minute.':'.$second;
            }else{
                $result = $hour.'小时'.$minute.'分钟';
            }
        }
        return $result;
    }

    /**
     * 根据给定符号截取字符串的指定部分
     * @param string $str  需要截取的字符串
     * @param string $sign 需要截取的符号
     * @param int $number  如是正数以0为起点从左向右截  负数则从右向左截
     * @return string      返回截取的内容
     */
    public static function cut_str($str, $sign, $number)
    {
        $array = explode($sign, $str);    // 转为数组
        $length = count($array);          // 数组长度
        if ($number < 0) {
            $new_array = array_reverse($array);    // 反序数组
            $abs_number = abs($number);   // 取绝对值
            if ($abs_number > $length) {
                return 'error';
            } else {
                return $new_array[$abs_number - 1];
            }
        } else {
            if ($number >= $length) {
                return 'error';
            } else {
                return $array[$number];
            }
        }
    }

    /**
     * 互动消息日期转换
     * @Description: 将时间转换为几秒前、几分钟前、几小时前、几天前 、当年发布的其他视频为X月X日、发布的当年之前视频为X年X月X日
     * @Author: Yang
     * @param $the_time 需要转换的时间
     * @return string
     */
    public static function timeTran($the_time)
    {
        $now_time = date("Y-m-d H:i:s", time());
        $now_time = strtotime($now_time);
        $show_time = strtotime($the_time);
        $dur = $now_time - $show_time;
        if ($dur < 0) {
            return $the_time;
        } else {
            if ($dur < 60) {
                return '刚刚';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 604800) { // 7天内
                            return floor($dur / 86400) . '天前';
                        } else {
                            if($dur < 31536000){//一年
                                if(date('Y',$show_time) == date('Y',time())){
                                    return date('m-d', $show_time);
                                }else{
                                    return date('Y-m-d', $show_time);
                                }
                            }else{
                                return date('Y-m-d', $show_time);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     *  播放超过10000转1w
     * @param $people
     * @return string
     */
    public static function tenThousand($playCount)
    {
        if($playCount > 10000){
            return sprintf("%.1f", $playCount /10000).'W';
        }
        return  (string)$playCount;
    }

    /**
     * 数字格式化
     * @param $num int 数字
     * @param $flag bool 是否显示W
     * @return string
     */
    public static function ConvertNumFormat ($num, $flag = false)
    {
        if ($flag == false)
            return number_format($num);
        if($num < 10000){
            return $num;
        }
        $suffix = "";
        if ($flag == true && $num >= 10000 && $num < 100000001)
        {
            $suffix = "W";
            $num = $num / (10000);
        }
        if ($flag == true && $num >= 100000000)
        {
            $suffix = "亿";
            $num = $num / (100000000);
        }
        return sprintf("%.2f", $num) . $suffix;
    }

    /**
     * 百分数保留两位小数 四舍五入
     * @param $num
     * @return float
     */
    public static function percentageNum($num): float
    {
        return round ($num, 2);
    }

    /**
     * 自定义错误信息输出
     * @param $describe  //描述
     * @param $data      //数组格式数据
     * @param $textName  //文本名称
     */
    public static function errorMessagePut($describe,$data,$textName='test'){
        //自定义日志位置开始
        $log = new Logger('error');    //可选参数自己查monolog ,lemun的日志类是基于monolog的
        $logPath = storage_path('/logs/info/'.$textName.'_'.date('Y-m-d').'.log');
        $handler = (new StreamHandler($logPath))->setFormatter(new LineFormatter(null, null, true, true));
        $log->pushHandler($handler);
        $log->info($describe,$data);
        //自定义日志位置结束
    }


    /**
     * 获取折扣
     * @param $price            //原价
     * @param $discountPrice    //优惠价格
     * @return string           //返回折扣
     */
    public static function getDiscount($price,$discountPrice)
    {
        if ($discountPrice === 0 || $price == $discountPrice || $discountPrice ==='0'){
            return '无折扣';
        }
        $num = $discountPrice/$price*10;
        $num = floatval(substr($num,0,3));
        return  $num.'折';
    }


    /**
     * 数值格式化
     * @param $nums
     * @return string
     */
    public static function numScaler ($nums)
    {
        $c=10000;
        $d=100000000;
        if ($nums >= $d) {
            return round($nums/$d,2).'亿';
        } elseif ($nums>=$c && $nums<$d) {
            return round($nums/$c,2).'w';
        } else {
            return $nums;
        }
    }

    /**
     * @param $url
     * @param string $method
     * @param null $postfields
     * @param array $headers
     * @param bool $debug
     * @return mixed
     */
    public static function httpRequestCode($url, $method="GET", $postfields = null, $headers = array(), $debug = false)
    {
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method);
        switch ($method) {
            case "POST":
            case "DELETE":
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
            curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        }
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        return $http_code;
    }

    /**
     * svga 版本号
     * @param $num   //初始值 100
     * @return string
     */
    public static function giftVersionNum($num){
        $firstNum  = 0;
        $secondNum = 0;
        if($num<1000){
            $firstNum  = substr($num,0,1);
            $secondNum = substr($num,1,1);
        }elseif ($num>=1000 && $num<10000){
            $firstNum  = substr($num,0,2);
            $secondNum = substr($num,2,1);
        }elseif ($num>=10000 && $num<100000){
            $firstNum  = substr($num,0,3);
            $secondNum = substr($num,3,1);
        }elseif ($num>=100000 && $num<1000000 ){
            $firstNum  = substr($num,0,4);
            $secondNum = substr($num,4,1);
        }
        $lastNum   = substr($num,-1);
        $str = $firstNum.'.'.$secondNum.'.'.$lastNum;
        return   $str;
    }


    /**
     * 版本号转整数 例如　1.0.0=001.000.000=001000000=1000000
     * @param string $ver
     * @return int
     */
    public static function versionToInteger($ver) {
        $ver = explode(".", $ver);
        $v1 = sprintf('%03s', (int) $ver[0] ?? 0);
        $v2 = sprintf('%03s', (int) $ver[1] ?? 0);
        $v3 = sprintf('%03s', (int) $ver[2] ?? 0);
        return (int) "{$v1}{$v2}{$v3}";
    }

    /**
     * 整数版本号转字符串　例如 1000000=001000000=001.000.000=1.0.0
     * @param int $ver
     * @return string
     */
    public static  function versionToString($ver) {
        if($ver > 999) {
            if($ver > 999999) {
                $ver = $ver . "";
                $v3 = (int) substr($ver, -3);
                $v2 = (int) substr($ver, -6, 3);
                $v1 = (int) substr($ver, 0, strlen($ver) - 6);
            } else {
                $ver = $ver . "";
                $v3 = (int) substr($ver, -3);
                $v2 = (int) substr($ver, 0, strlen($ver) - 3);
                $v1 = 0;
            }
        } else {
            $v3 = $ver;
            $v2 = 0;
            $v1 = 0;
        }
        return "{$v1}.{$v2}.{$v3}";
    }

    /**
     * 获取毫秒
     * @return float
     */
    public static function microsecond()
    {
        $t = explode(" ", microtime());
        $microsecond = round(round($t[1].substr($t[0],2,3)));
        return $microsecond;
    }

    /**
     * redis select db
     * cluster not select
     * @return mixed
     * @throws \Exception
     */
    public static function redisSelectDb()
    {
        $config = config('database.redis');
        if (isset($config['cluster']) && $config['cluster'] == true) {
            return true;
        }
        return false;
    }

    /**
     * 监听key过期脚本Redis链接 - 兼容单机测试服务器
     * @return \Redis
     * @throws \Exception
     */
    public static function getListeningRedisNodeInstance()
    {
        $db_config = config('database.redis');
        try{
            if (isset($db_config['cluster']) && $db_config['cluster'] == true) {
                $redisNodeConfig = config('RedisListeningNodeConfig');
                $host       = $redisNodeConfig['host'];
                $port       = $redisNodeConfig['port'];
                $password   = $redisNodeConfig['password'];
            }else{
                $host       = $db_config['default']['host'];
                $port       = $db_config['default']['port'];
                $password   = $db_config['default']['password'];
            }

            $redis = new \Redis();
            $redis->connect($host, $port);
            $redis->auth($password);
            $redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
            return $redis;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取Redis监听过期key 执行字符串
     * @param $rdb
     * @return string
     * @throws \Exception
     */
    public static function getRedisKeyEvent($rdb)
    {
        try{
            $config = config('database.redis');
            if (isset($config['cluster']) && $config['cluster'] == true) {
                $KeyEvent = '__keyevent@*__:expired';
            }else{
                $KeyEvent = '__keyevent@'.$rdb.'__:expired';
            }
            return $KeyEvent;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取明星直播的运营账号配置
     * @param $type
     * @param $field
     * @param $first
     * @param $index
     * @return array
     * @throws \Exception
     */
    public static function getOperateUser($type = 'all',$field = '',$first = false,$index = 0){
        $operateData = Config::get('OperateAccountConfig')[$type];
        if (empty($field) && !$first) {
           return $operateData;
        }
        if($first){
            $operateData = Config::get('OperateAccountConfig')['all'];
            $operateData = array_column($operateData,null,$field);
            if(!isset($operateData[$index]) || empty($operateData)){
                return [];
            }
            return $operateData[$index];
        }
        $operateData = array_column($operateData,$field);
        return $operateData;
    }

    /**
     * @param $str
     * @return array|string|string[]|null
     * 提取字符串中数字
     */
    public static function number($str)
    {
        return preg_replace('/[^\.0123456789]/s', '', $str);
    }

    /**
     * 获取lang指定的文案
     * @param $langType
     * @param $field
     * @return string
     * @throws \Exception
     */
    public static function getLangInfo($langType = '',$field = ''){
        return !empty($langType) ? trans($langType.".".$field) : "";
    }



    /**
     * 校验IP是否在白名单内
     * @return bool
     */
    public static function checkIp()
    {
        $user_IP = get_real_ip();
        $ipC = Config::get('BrandConfig')['ipWlist'];
        if (empty($ipC)) {
            return false;
        }
        //没有开启白名单验证  返回true
        if (!$ipC['ifFilter']) {
            return true;
        }
        //校验IP是否在白名单内   在返回true
        if (in_array($user_IP, $ipC['wlist'])) {
            return true;
        }
        //校验 IP网段    是否在允许请求内   在就返回true
        if (isset($ipC['segment']) && !empty($ipC['segment'])) {
            foreach ($ipC['segment'] as $value) {
                if (self::ip_in_network($user_IP, $value)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 校验ip
     * @param $ip
     * @param $network
     * @return bool
     */
    public static function ip_in_network($ip, $network)
    {
        $ip = (double)(sprintf("%u", ip2long($ip)));
        $s = explode('/', $network);
        $network_start = (double)(sprintf("%u", ip2long($s[0])));
        $network_len = pow(2, 32 - $s[1]);
        $network_end = $network_start + $network_len - 1;
        if ($ip >= $network_start && $ip <= $network_end) {
            return true;
        }
        return false;
    }

}
